using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using ThridGroup.ERP.Application.Contracts.DTO;
using ThridGroup.ERP.Application.Contracts.ProductionSystem;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ThridGroup.ERP.Web.Areas.ProductionSystem.Controllers
{
    [Area("ProductionSystem")]
    [Route("ProductionSystem/[controller]")]
    public class ProductionReportingController : AbpController
    {
        private readonly IProductionReportingService _productionReportingService;
        private readonly ILogger<ProductionReportingController> _logger;

        public ProductionReportingController(
            IProductionReportingService productionReportingService,
            ILogger<ProductionReportingController> logger)
        {
            _productionReportingService = productionReportingService;
            _logger = logger;
        }

        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            _logger.LogInformation("访问生产报工管理页面");
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id, string action = "edit")
        {
            try
            {
                ProductionReportingDto model = null;
                
                if (id.HasValue && id.Value > 0)
                {
                    model = await _productionReportingService.GetProductionReporting(id.Value);
                }
                
                // 设置查看模式
                ViewBag.IsViewMode = action?.ToLower() == "view";
                
                return View(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载编辑页面失败，ID：{id}");
                TempData["ErrorMessage"] = $"加载页面失败：{ex.Message}";
                return RedirectToAction("Index");
            }
        }

        [HttpGet]
        [Route("GetProductionReportings")]
        public async Task<IActionResult> GetProductionReportings(
            string productionWorkOrderCode = null, 
            string productMaterialCode = null, 
            string reporter = null, 
            int page = 1, 
            int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始获取生产报工列表, 页码: {page}, 每页数量: {limit}, 筛选条件: 工单编号={productionWorkOrderCode}, 物料编码={productMaterialCode}, 报工人={reporter}");
                
                List<ProductionReportingDto> allData;
                try
                {
                    allData = await _productionReportingService.GetProductionReportings();
                    _logger.LogInformation($"从服务层获取生产报工列表成功，共获取{allData?.Count ?? 0}条记录");
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, "从服务层获取生产报工列表失败");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<ProductionReportingDto>() });
                }
                
                if (allData == null)
                {
                    _logger.LogWarning("服务层返回的生产报工列表为null");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<ProductionReportingDto>() });
                }

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(productionWorkOrderCode))
                {
                    allData = allData.Where(x => x.ProductionWorkOrderCode.Contains(productionWorkOrderCode, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(productMaterialCode))
                {
                    allData = allData.Where(x => x.ProductMaterialCode.Contains(productMaterialCode, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(reporter))
                {
                    allData = allData.Where(x => x.Reporter.Contains(reporter, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                // 按创建时间倒序排序
                var orderedData = allData.OrderByDescending(x => x.RecordCreateTime).ToList();
                
                // 计算总记录数
                int totalCount = orderedData.Count;
                
                // 进行分页
                var pagedData = orderedData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"成功获取生产报工列表，总记录数: {totalCount}, 当前页记录数: {pagedData.Count}");
                
                return Json(new { 
                    code = 0, 
                    msg = "获取成功", 
                    count = totalCount, 
                    data = pagedData 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产报工列表失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<ProductionReportingDto>() });
            }
        }

        [HttpGet]
        [Route("Get/{id}")]
        public async Task<IActionResult> GetProductionReporting(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取生产报工，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的生产报工ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var model = await _productionReportingService.GetProductionReporting(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的生产报工，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的生产报工" });
                }

                _logger.LogInformation($"成功获取生产报工，ID：{id}");
                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取生产报工失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("AddProductionReporting")]
        public async Task<IActionResult> AddProductionReporting([FromBody] ProductionReportingDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始添加生产报工，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("添加生产报工时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductionWorkOrderCode))
                {
                    _logger.LogWarning("添加生产报工时工单编号为空");
                    return Json(new { code = 1, msg = "生产工单编号不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductMaterialCode))
                {
                    _logger.LogWarning("添加生产报工时物料编码为空");
                    return Json(new { code = 1, msg = "产品物料编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductMaterialName))
                {
                    _logger.LogWarning("添加生产报工时物料名称为空");
                    return Json(new { code = 1, msg = "产品物料名称不能为空" });
                }

                if (dto.ReportingQuantity <= 0)
                {
                    _logger.LogWarning("添加生产报工时报工数量无效");
                    return Json(new { code = 1, msg = "报工数量必须大于0" });
                }

                if (string.IsNullOrWhiteSpace(dto.Reporter))
                {
                    _logger.LogWarning("添加生产报工时报工人为空");
                    return Json(new { code = 1, msg = "报工人不能为空" });
                }

                int result = await _productionReportingService.AddProductionReporting(dto);
                _logger.LogInformation($"生产报工添加成功，返回ID：{result}");
                return Json(new { code = 0, msg = "添加成功", data = new { id = result } });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加生产报工失败");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("UpdateProductionReporting")]
        public async Task<IActionResult> UpdateProductionReporting([FromBody] ProductionReportingDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始更新生产报工，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("更新生产报工时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (dto.Id <= 0)
                {
                    _logger.LogWarning($"更新生产报工时ID无效：{dto.Id}");
                    return Json(new { code = 1, msg = "无效的生产报工ID" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductionWorkOrderCode))
                {
                    return Json(new { code = 1, msg = "生产工单编号不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductMaterialCode))
                {
                    return Json(new { code = 1, msg = "产品物料编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProductMaterialName))
                {
                    return Json(new { code = 1, msg = "产品物料名称不能为空" });
                }

                if (dto.ReportingQuantity <= 0)
                {
                    return Json(new { code = 1, msg = "报工数量必须大于0" });
                }

                if (string.IsNullOrWhiteSpace(dto.Reporter))
                {
                    return Json(new { code = 1, msg = "报工人不能为空" });
                }

                int result = await _productionReportingService.UpdateProductionReporting(dto);
                _logger.LogInformation($"生产报工更新成功，ID：{result}");
                return Json(new { code = 0, msg = "更新成功", data = new { id = result } });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新生产报工失败");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> DeleteProductionReporting(int id)
        {
            try
            {
                _logger.LogInformation($"开始删除生产报工，ID：{id}");
                
                if (id <= 0)
                {
                    _logger.LogWarning($"删除生产报工时ID无效：{id}");
                    return Json(new { code = 1, msg = "无效的生产报工ID" });
                }

                await _productionReportingService.DeleteProductionReporting(id);
                _logger.LogInformation($"生产报工删除成功，ID：{id}");
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除生产报工失败，ID：{id}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }
    }
} 